#include "header.h"
#include <iostream>
using namespace std;
#define BUFFER_SIZE 1024
int main()
{
    const char * sourceIP = "127.0.0.1";
    const char * sourcePort = "8080";

    // const char * sourceIP = "8.148.75.183";
    //const char * sourcePort = "9031";
    int clientfd = socket(AF_INET, SOCK_STREAM, 0);
    ERROR_CHECK(clientfd, 0, "socket");

    struct sockaddr_in serveraddr;
    memset(&serveraddr, 0, sizeof(serveraddr));

    serveraddr.sin_family = AF_INET;
    serveraddr.sin_port =htons(atoi(sourcePort));
    serveraddr. sin_addr.s_addr = inet_addr(sourceIP);

    int ret = connect(clientfd, (const struct sockaddr*)&serveraddr, sizeof(serveraddr));
    //ERROR_CHECK(ret, 0, "bind");

    while(1){
        char buffer[BUFFER_SIZE];
        memset(buffer, 0, sizeof(buffer));
        cout << "请输入消息：" << endl;
        if (fgets(buffer, BUFFER_SIZE, stdin) != NULL) {
            // 移除末尾的换行符
            //    buffer[strcspn(buffer, "\n")] = '\0';
            // 现在可以通过socket发送buffer中的内容
            int ret = send(clientfd, buffer, strlen(buffer), 0);
            printf("\nsend %d bytes.\n", ret);
        };

        memset(buffer, 0, sizeof(buffer));
        ret = recv(clientfd, buffer, sizeof(buffer),0);
        if(ret != 0)
            cout << "服务器发来：" << buffer << endl; 
        else{
            cout << "服务器关闭" << endl;
            break;
        }
    }

    return 0;
};


